<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🛏️ 健康床监控系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
            animation: pulse 2s infinite;
        }
        
        .status-online {
            background-color: #2ecc71;
        }
        
        .status-offline {
            background-color: #e74c3c;
        }
        
        .status-connecting {
            background-color: #f39c12;
        }
        
        .status-error {
            background-color: #e74c3c;
            animation: pulse 1s infinite;
        }
        
        .status-unknown {
            background-color: #95a5a6;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        @keyframes flash {
            0% { background-color: transparent; }
            50% { background-color: rgba(46, 204, 113, 0.3); }
            100% { background-color: transparent; }
        }
        
        .refresh-indicator {
            font-size: 0.85em;
            color: #fff;
            background-color: rgba(0, 0, 0, 0.2);
            padding: 5px 10px;
            border-radius: 15px;
            margin-top: 10px;
            display: inline-block;
            transition: all 0.3s ease;
        }
        
        .refresh-active {
            background-color: rgba(46, 204, 113, 0.8);
            color: white;
            animation: flash 1s;
        }
        
        .debug-panel {
            position: fixed;
            top: 100px;
            right: 20px;
            background-color: rgba(255, 255, 255, 0.95);
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            padding: 15px;
            max-width: 400px;
            max-height: 80vh;
            overflow-y: auto;
            z-index: 1000;
        }
        
        .debug-panel h3 {
            margin-top: 0;
            border-bottom: 1px solid #ddd;
            padding-bottom: 8px;
        }
        
        .debug-panel h4 {
            margin: 10px 0 5px;
            color: #3498db;
        }
        
        .debug-content {
            font-family: monospace;
            font-size: 12px;
            white-space: pre-wrap;
            word-break: break-all;
        }
        
        .dashboard {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
            position: relative; /* 为加载指示器设置相对定位 */
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f1f2f6;
        }
        
        .card-title {
            font-size: 1.3em;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .card-icon {
            font-size: 1.5em;
            margin-right: 10px;
        }
        
        .data-display {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin: 10px 0;
            font-family: 'Courier New', monospace;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .vital-signs {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }
        
        .vital-item {
            text-align: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #3498db;
            transition: background-color 0.5s ease;
        }
        
        .vital-value {
            font-size: 2em;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .vital-label {
            color: #7f8c8d;
            font-size: 0.9em;
            margin-top: 5px;
        }
        
        .controls {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .control-group {
            margin-bottom: 20px;
        }
        
        .control-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .slider {
            width: 100%;
            height: 8px;
            border-radius: 5px;
            background: #ddd;
            outline: none;
            -webkit-appearance: none;
        }
        
        .slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #3498db;
            cursor: pointer;
        }
        
        .speed-selector {
            width: 100%;
            padding: 8px 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            background: white;
            font-size: 1em;
            color: #2c3e50;
            cursor: pointer;
            margin-bottom: 10px;
        }
        
        .speed-selector:focus {
            border-color: #3498db;
            outline: none;
        }
        
        .btn {
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 1em;
            transition: all 0.3s ease;
            margin: 5px;
        }
        
        .btn:hover {
            transform: scale(1.05);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
        }
        
        .btn-danger {
            background: linear-gradient(45deg, #e74c3c, #c0392b);
        }
        
        .btn-success {
            background: linear-gradient(45deg, #27ae60, #229954);
        }
        
        .timestamp {
            font-size: 0.8em;
            color: #95a5a6;
            text-align: right;
            margin-top: 10px;
        }
        
        .loading {
            text-align: center;
            color: #7f8c8d;
            font-style: italic;
        }
        
        .error {
            color: #e74c3c;
            background: #fadbd8;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        
        .status-active {
            color: #2ecc71;
            font-weight: bold;
        }
        
        .status-inactive {
            color: #e74c3c;
            font-weight: bold;
        }

        .auto-control-status {
            margin-top: 15px;
        }

        .auto-control-status .status-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .auto-control-status .status-item span {
            margin-right: 10px;
        }
        
        .cached-data {
            color: #f39c12 !important;
            font-style: italic;
        }
        
        .loading-indicator {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0,0,0,0.1);
            border-radius: 50%;
            border-top-color: #3498db;
            animation: spin 1s ease-in-out infinite;
            margin-left: 10px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .refresh-button {
            background: transparent;
            border: none;
            color: #3498db;
            cursor: pointer;
            font-size: 0.9em;
            padding: 0;
            margin-left: 10px;
        }
        
        .refresh-button:hover {
            color: #2980b9;
            text-decoration: underline;
        }
        
        /* 数据更新动画效果 */
        .data-updated {
            animation: highlight-update 1s ease;
        }
        
        @keyframes highlight-update {
            0% { background-color: rgba(46, 204, 113, 0.2); }
            100% { background-color: #f8f9fa; }
        }
        
        /* 数值变化高亮效果 */
        .highlight-change {
            animation: text-highlight 1.5s ease;
        }
        
        @keyframes text-highlight {
            0% { color: #e74c3c; }
            100% { color: #2c3e50; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🛏️ 健康床监控系统</h1>
            <p>
                <span id="connectionStatus" class="status-indicator status-offline"></span>
                系统状态: <span id="statusText">连接中...</span>
                <button onclick="testDataDisplay()" class="btn btn-sm" style="margin-left: 15px; padding: 5px 10px; font-size: 0.8em; background: linear-gradient(45deg, #e67e22, #d35400);">测试数据刷新</button>
                <button onclick="toggleDebugPanel()" class="btn btn-sm" style="margin-left: 5px; padding: 5px 10px; font-size: 0.8em;">调试面板</button>
            </p>
            <div id="refreshIndicator" class="refresh-indicator">数据未刷新</div>
        </div>
        
        <!-- 调试面板 -->
        <div id="debugPanel" class="debug-panel" style="display: none;">
            <h3>数据调试面板 <button onclick="toggleDebugPanel()" style="float:right; background:none; border:none; cursor:pointer; font-size:1.2em;">×</button></h3>
            <div class="debug-content">
                <h4>原始API数据结构</h4>
                <div id="apiStructure" style="font-family: monospace; font-size: 11px; background: #f5f5f5; padding: 8px; border-radius: 4px; margin-bottom: 10px; max-height: 150px; overflow-y: auto;">等待数据...</div>
                
                <h4>设备1数据</h4>
                <div id="device1Debug" style="font-family: monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; max-height: 200px; overflow-y: auto;">等待数据...</div>
                
                <h4>设备2数据</h4>
                <div id="device2Debug" style="font-family: monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; max-height: 200px; overflow-y: auto;">等待数据...</div>
                
                <h4>数据路径测试</h4>
                <div id="dataPathTest" style="font-family: monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; background: #f0f8ff; padding: 8px; border-radius: 4px; border-left: 3px solid #3498db;">等待测试...</div>
                
                <h4>占位符检查</h4>
                <div id="placeholderTest" style="font-family: monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; background: #fff0f0; padding: 8px; border-radius: 4px; border-left: 3px solid #e74c3c;">等待检查...</div>
                
                <h4>上次数据刷新</h4>
                <div id="lastUpdateTime">从未刷新</div>
            </div>
        </div>
                
                <h4>上次数据刷新</h4>
                <div id="lastUpdateTime">从未刷新</div>
                
                <div style="margin-top: 15px;">
                    <button onclick="testDataDisplay()" class="btn" style="padding: 5px 10px; font-size: 0.9em; width: 100%;">重新获取测试数据</button>
                </div>
            </div>
        </div>
        
        <div class="dashboard">
            <!-- 生理监测卡片 -->
            <div class="card">
                <div class="card-header">
                    <span class="card-icon">❤️</span>
                    <span class="card-title">生理监测</span>
                </div>
                <div class="vital-signs" id="vitalSigns">
                    <div class="vital-item">
                        <div class="vital-value" id="heartRate">--</div>
                        <div class="vital-label">心率 (bpm)</div>
                    </div>
                    <div class="vital-item">
                        <div class="vital-value" id="breathRate">--</div>
                        <div class="vital-label">呼吸频率</div>
                    </div>
                </div>
                <div class="timestamp" id="vitalTimestamp">数据更新时间: --</div>
            </div>
            
            <!-- 环境监测卡片 -->
            <div class="card">
                <div class="card-header">
                    <span class="card-icon">🌡️</span>
                    <span class="card-title">环境监测</span>
                </div>
                <div class="vital-signs" id="environmentData">
                    <div class="vital-item">
                        <div class="vital-value" id="roomTemp">--</div>
                        <div class="vital-label">室温 (°C)</div>
                    </div>
                    <div class="vital-item">
                        <div class="vital-value" id="humidity">--</div>
                        <div class="vital-label">湿度 (%)</div>
                    </div>
                </div>
                <div class="timestamp" id="envTimestamp">数据更新时间: --</div>
            </div>
        </div>
        
        <!-- 床板控制面板 -->
        <div class="controls">
            <div class="card-header">
                <span class="card-icon">🎛️</span>
                <span class="card-title">床板控制</span>
            </div>
            
            <div class="control-group">
                <label for="angleSlider">床板角度: <span id="angleValue">0</span>°</label>
                <input type="range" id="angleSlider" class="slider" min="0" max="90" value="0">
            </div>
            
            <div class="control-group">
                <label for="speedSelect">调节速度: </label>
                <select id="speedSelect" class="speed-selector">
                    <option value="1">1级 (慢速)</option>
                    <option value="2">2级 (中速)</option>
                    <option value="3">3级 (快速)</option>
                </select>
            </div>
            
            <div class="control-group">
                <button class="btn" onclick="setBedPosition('flat')">🛏️ 平躺模式</button>
                <button class="btn" onclick="setBedPosition('raised')">📐 抬起模式</button>
                <button class="btn btn-success" onclick="applyAngle()">✅ 应用角度</button>
                <button class="btn btn-danger" onclick="emergencyStop()">🛑 紧急停止</button>
            </div>
            
            <!-- 自动控制状态 -->
            <div class="control-group auto-control-section">
                <div class="card-header" style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 15px;">
                    <span class="card-icon">🤖</span>
                    <span class="card-title">自动控制</span>
                </div>
                <div class="auto-control-status">
                    <div class="status-item">
                        <span>坐起自动调整:</span>
                        <span id="autoControlStatus" class="status-indicator">未知</span>
                        <button id="toggleAutoControl" class="btn btn-sm" onclick="toggleAutoControl()">加载中...</button>
                    </div>
                    <div class="status-description" style="margin-top: 10px; font-size: 0.9em; color: #666;">
                        启用后，系统将自动检测坐起状态并调整床板角度至30°
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let isConnected = false;
        let dataPollingService = null;
        let autoControlPollingService = null;
        let lastDeviceData = null;
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            console.log('🚀 健康床监控系统启动...');
            
            // 初始化轮询服务
            initPollingServices();
            
            // 角度滑块事件
            document.getElementById('angleSlider').addEventListener('input', function() {
                document.getElementById('angleValue').textContent = this.value;
            });
            
            // 设置页面卸载时的清理
            window.addEventListener('beforeunload', clearPollingServices);
        });
        
        // 创建轮询服务工具
        function createPollingService(fetchFn, interval, onSuccess, onError, initialDelay = 0) {
            let timerId = null;
            let isRunning = false;
            let retryCount = 0;
            let maxRetryCount = 3;
            let lastSuccessTime = 0;
            
            // 自适应重试间隔（指数退避算法）
            function getRetryDelay() {
                return Math.min(1000 * Math.pow(2, retryCount), 30000); // 最长30秒
            }
            
            // 执行轮询
            async function poll() {
                if (!isRunning) return;
                
                try {
                    const data = await fetchFn();
                    
                    // 成功处理
                    retryCount = 0;
                    lastSuccessTime = Date.now();
                    if (onSuccess) onSuccess(data);
                    
                    // 安排下一次轮询
                    if (isRunning) {
                        timerId = setTimeout(poll, interval);
                    }
                } catch (error) {
                    // 错误处理
                    retryCount++;
                    console.error(`轮询错误 (重试 ${retryCount}/${maxRetryCount}):`, error);
                    
                    if (onError) onError(error);
                    
                    // 如果重试次数小于最大次数，使用指数退避重试
                    if (retryCount <= maxRetryCount) {
                        const retryDelay = getRetryDelay();
                        console.log(`将在 ${retryDelay}ms 后重试...`);
                        timerId = setTimeout(poll, retryDelay);
                    } else {
                        // 超过最大重试次数，恢复正常轮询间隔
                        retryCount = 0;
                        timerId = setTimeout(poll, interval);
                    }
                }
            }
            
            // 启动轮询
            function start() {
                if (!isRunning) {
                    isRunning = true;
                    console.log(`轮询服务启动，间隔: ${interval}ms`);
                    
                    // 初始延迟或立即执行
                    if (initialDelay > 0) {
                        timerId = setTimeout(poll, initialDelay);
                    } else {
                        poll(); // 立即执行第一次
                    }
                }
                return { stop, isActive };
            }
            
            // 停止轮询
            function stop() {
                if (isRunning) {
                    isRunning = false;
                    if (timerId) {
                        clearTimeout(timerId);
                        timerId = null;
                    }
                    console.log('轮询服务已停止');
                }
            }
            
            // 检查是否活跃
            function isActive() {
                return isRunning;
            }
            
            // 获取状态信息
            function getStatus() {
                return {
                    isRunning,
                    retryCount,
                    lastSuccessTime,
                    timeSinceLastSuccess: lastSuccessTime ? Date.now() - lastSuccessTime : null
                };
            }
            
            return { start, stop, isActive, getStatus };
        }
        
        // 初始化所有轮询服务
        function initPollingServices() {
            // 设备数据轮询
            dataPollingService = createPollingService(
                fetchDeviceData,         // 数据获取函数
                8000,                    // 轮询间隔 8秒
                handleDeviceDataWithDebugger, // 使用调试包装器
                handleDeviceDataError    // 错误回调
            ).start();
            
            // 自动控制状态轮询 (每30秒)
            autoControlPollingService = createPollingService(
                fetchAutoControlStatus,  // 数据获取函数
                30000,                   // 轮询间隔 30秒
                updateAutoControlUI,     // 成功回调
                (error) => console.error('自动控制状态获取失败:', error), // 错误回调
                2000                     // 初始延迟 2秒 (避免与设备数据轮询同时发起)
            ).start();
        }
        
        // 清除所有轮询服务
        function clearPollingServices() {
            if (dataPollingService) {
                dataPollingService.stop();
            }
            if (autoControlPollingService) {
                autoControlPollingService.stop();
            }
        }
        
        // 设备数据获取函数 - 从后端获取已处理和格式化的数据
        // 注意：所有数据筛选、验证、格式化等逻辑已全部移至后端，前端只负责显示
        async function fetchDeviceData() {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 8000); // 8秒超时
            
            try {
                console.log('📡 正在获取设备数据...');
                // 更新连接状态为"正在请求"
                updateConnectionStatus('connecting');
                
                // 添加时间戳参数阻止缓存
                const cacheBuster = new Date().getTime();
                const response = await fetch(`/api/current-data?t=${cacheBuster}`, { 
                    signal: controller.signal,
                    cache: 'no-store', // 不使用缓存
                    headers: {
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    }
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    updateConnectionStatus('error');
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 更新连接状态为"已连接"
                updateConnectionStatus('online');
                
                const data = await response.json();
                return data;
            } catch (error) {
                clearTimeout(timeoutId);
                if (error.name === 'AbortError') {
                    throw new Error('请求超时，服务器响应时间过长');
                }
                throw error;
            }
        }
        
        // 调试工具包装的数据处理函数
        function handleDeviceDataWithDebugger(data) {
            console.log('🔍 使用调试工具分析数据...');
            
            // 为后端开发者提供原始数据参考
            console.log('📄 API原始响应:', JSON.stringify(data));
            
            // 使用调试工具处理数据
            if (window.dataDebugger) {
                const debugResult = window.dataDebugger.processResponse(data);
                
                // 分析数据是否符合预期结构
                if (debugResult.diagnostics.issues.length > 0) {
                    console.warn('⚠️ 数据结构问题:', debugResult.diagnostics.issues);
                    console.info('💡 建议解决方案:', debugResult.diagnostics.recommendations);
                } else {
                    console.log('✅ 数据结构符合预期');
                }
            }
            
            // 继续正常的数据处理流程
            handleDeviceDataSuccess(data);
        }
        
        // 设备数据成功处理 - 简化版
        function handleDeviceDataSuccess(data) {                
            console.log('📊 收到设备数据');
            
            // 简单的有效性检查
            if (!data || typeof data !== 'object') {
                console.error('❌ 数据格式错误：不是有效的对象');
                return;
            }
            
            // 记录接收到的数据类型
            if (data.Data && data.Data.List && Array.isArray(data.Data.List.PropertyStatusInfo)) {
                console.log('✅ 收到物模型格式数据');
            } else if (data.traditional_format && data.traditional_format.devices) {
                console.log('✅ 收到传统格式数据');
            } else if (data.devices) {
                console.log('✅ 收到直接设备数据');
            }
            
            // 更新调试面板
            updateDebugPanel(data);
        
            // 保存最新数据
            lastDeviceData = data;
            
            // 更新连接状态和显示数据
            updateConnectionStatus('online');
            updateDisplayData(data);
        }
        
        // 设备数据错误处理
        function handleDeviceDataError(error) {
            console.error('❌ 数据获取失败:', error);
            updateConnectionStatus('offline');
            
            // 如果存在缓存数据，继续使用但显示是缓存数据
            if (lastDeviceData) {
                updateDisplayData(lastDeviceData, true); // true表示使用缓存数据
            }
        }
        
        // 更新连接状态
        function updateConnectionStatus(status) {
            const statusIndicator = document.getElementById('connectionStatus');
            const statusText = document.getElementById('statusText');
            
            switch (status) {
                case 'online':
                    statusIndicator.className = 'status-indicator status-online';
                    statusText.textContent = '在线';
                    console.log('✅ 系统连接正常');
                    break;
                case 'offline':
                    statusIndicator.className = 'status-indicator status-offline';
                    statusText.textContent = '离线';
                    console.log('❌ 系统连接断开');
                    break;
                case 'connecting':
                    statusIndicator.className = 'status-indicator status-connecting';
                    statusText.textContent = '连接中...';
                    console.log('🔄 正在连接系统...');
                    break;
                case 'error':
                    statusIndicator.className = 'status-indicator status-error';
                    statusText.textContent = '连接错误';
                    console.log('⚠️ 系统连接错误');
                    break;
                default:
                    statusIndicator.className = 'status-indicator status-unknown';
                    statusText.textContent = '未知状态';
                    console.log('❓ 系统状态未知');
            }
        }                // 更新显示数据
        function updateDisplayData(data, isCachedData = false) {
            const now = new Date().toLocaleString('zh-CN');
            const timestamp = isCachedData ? `缓存数据 (最后更新: ${now})` : `数据更新时间: ${now}`;
            
            try {
                console.log('🔄 显示后端处理的数据');
                
                // 获取数据来源
                let dataSource = '标准API数据';
                if (isCachedData) {
                    dataSource = '缓存数据';
                }
                
                // 直接显示物模型格式中的关键数据 (后端已处理好所有格式和验证)
                if (data && data.Data && data.Data.List && Array.isArray(data.Data.List.PropertyStatusInfo)) {
                    console.log('📊 显示物模型格式数据');
                    
                    // 从物模型数据中直接读取显示值
                    data.Data.List.PropertyStatusInfo.forEach(item => {
                        if (item.Identifier === 'radar_heartrate') {
                            updateElementText('heartRate', item.Value);
                        } 
                        else if (item.Identifier === 'radar_breath') {
                            updateElementText('breathRate', item.Value);
                        }
                        else if (item.Identifier === 'temp') {
                            updateElementText('roomTemp', item.Value);
                        }
                        else if (item.Identifier === 'humidity') {
                            updateElementText('humidity', item.Value);
                        }
                    });
                    
                    // 添加数据源标识
                    if (data.metadata && data.metadata.source) {
                        dataSource = data.metadata.source;
                    }
                }
                // 兼容传统格式
                else if (data.traditional_format && data.traditional_format.devices && data.traditional_format.devices.device1) {
                    console.log('📊 显示传统格式数据 (备用)');
                    
                    const device = data.traditional_format.devices.device1;
                    
                    // 直接使用传统格式中的格式化数据
                    updateElementText('heartRate', device.heart_rate);
                    updateElementText('breathRate', device.breath_rate);
                    updateElementText('roomTemp', device.temperature);
                    updateElementText('humidity', device.humidity);
                    
                    dataSource = '传统格式数据';
                }
                
                // 更新时间戳
                document.getElementById('vitalTimestamp').textContent = `${timestamp} (${dataSource})`;
                document.getElementById('envTimestamp').textContent = `${timestamp} (${dataSource})`;
                
                // 设置缓存指示器
                if (isCachedData) {
                    addCachedDataIndicator();
                } else {
                    removeCachedDataIndicator();
                }
                
                // 触发更新动画
                triggerUpdateAnimation();
                
            } catch (error) {
                console.error('❌ 数据显示更新失败:', error);
            }
        }
        
        // 所有数据格式化和验证工作已转移至后端
        // 前端只负责显示后端已经处理和格式化的数据

        // 触发数据更新动画效果
        function triggerUpdateAnimation() {
            const vitalItems = document.querySelectorAll('.vital-item');
            vitalItems.forEach(item => {
                // 添加动画类
                item.classList.add('data-updated');
                
                // 一段时间后移除动画类
                setTimeout(() => {
                    item.classList.remove('data-updated');
                }, 1000);
            });
            
            // 更新刷新指示器
            const refreshIndicator = document.getElementById('refreshIndicator');
            if (refreshIndicator) {
                const now = new Date();
                const timeString = now.toLocaleTimeString();
                refreshIndicator.textContent = `数据已刷新: ${timeString}`;
                refreshIndicator.classList.add('refresh-active');
                setTimeout(() => {
                    refreshIndicator.classList.remove('refresh-active');
                }, 1000);
            }
        }
        
        // 姿态状态映射功能已移至后端
        
        // 安全地更新元素文本 - 简化版本，不做数据处理
        function updateElementText(elementId, value) {
            const element = document.getElementById(elementId);
            if (element) {
                const oldValue = element.textContent;
                // 处理未定义或空值，显示占位符
                const newValue = (value === undefined || value === null || value === '') ? '--' : value;
                
                // 只有当值发生变化时才更新DOM
                if (oldValue !== String(newValue)) {
                    console.log(`更新元素 ${elementId}: "${oldValue}" -> "${newValue}"`);
                    element.textContent = newValue;
                    
                    // 添加短暂的高亮效果
                    element.classList.add('highlight-change');
                    setTimeout(() => {
                        element.classList.remove('highlight-change');
                    }, 1500);
                }
            } else {
                console.warn(`⚠️ 未找到元素: ${elementId}`);
            }
        }
        
        // 添加缓存数据指示
        function addCachedDataIndicator() {
            const indicators = document.querySelectorAll('.timestamp');
            indicators.forEach(element => {
                if (!element.classList.contains('cached-data')) {
                    element.classList.add('cached-data');
                }
            });
        }
        
        // 移除缓存数据指示
        function removeCachedDataIndicator() {
            const indicators = document.querySelectorAll('.timestamp');
            indicators.forEach(element => {
                element.classList.remove('cached-data');
            });
        }
        
        // 设置床板位置
        async function setBedPosition(position) {
            const speedLevel = document.getElementById('speedSelect').value;
            const angle = position === 'flat' ? 0 : 45; // 平躺0°，抬起45°
            
            try {
                console.log(`🛏️ 设置床板位置: ${position}, 角度: ${angle}°, 速度: ${speedLevel}级`);
                
                // 显示加载中状态
                const actionButtons = document.querySelectorAll('.control-group button');
                actionButtons.forEach(btn => btn.disabled = true);
                
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
                
                const response = await fetch('/api/adjust-bed', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        device_id: 'device1',
                        angle: angle,
                        speed_level: parseInt(speedLevel)
                    }),
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    console.log('✅ 床板位置设置成功');
                    log(`床板已设置为: ${position === 'flat' ? '平躺' : '抬起'}模式 (${angle}°, ${speedLevel}级)`, 'success');
                    
                    // 更新滑块位置
                    document.getElementById('angleSlider').value = angle;
                    document.getElementById('angleValue').textContent = angle;
                    
                    // 触发数据刷新
                    if (dataPollingService && dataPollingService.isActive()) {
                        try {
                            const newData = await fetchDeviceData();
                            handleDeviceDataSuccess(newData);
                        } catch (error) {
                            console.error('调整后数据刷新失败:', error);
                        }
                    }
                } else {
                    console.error('❌ 床板位置设置失败:', result.error);
                    log(`床板设置失败: ${result.error}`, 'error');
                }
                
            } catch (error) {
                console.error('❌ 床板控制错误:', error);
                log(`床板控制错误: ${error.message}`, 'error');
            } finally {
                // 恢复按钮状态
                const actionButtons = document.querySelectorAll('.control-group button');
                actionButtons.forEach(btn => btn.disabled = false);
            }
        }
        
        // 应用角度设置
        async function applyAngle() {
            const angle = document.getElementById('angleSlider').value;
            const speedLevel = document.getElementById('speedSelect').value;
            
            try {
                console.log(`📐 设置床板角度: ${angle}°, 速度级别: ${speedLevel}`);
                
                // 显示加载中状态
                const actionButtons = document.querySelectorAll('.control-group button');
                actionButtons.forEach(btn => btn.disabled = true);
                
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
                
                const response = await fetch('/api/adjust-bed', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        device_id: 'device1',
                        angle: parseInt(angle),
                        speed_level: parseInt(speedLevel)
                    }),
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    console.log('✅ 床板角度设置成功');
                    log(`床板角度已设置为: ${angle}°, 速度: ${speedLevel}级`, 'success');
                    
                    // 触发数据刷新
                    if (dataPollingService && dataPollingService.isActive()) {
                        try {
                            const newData = await fetchDeviceData();
                            handleDeviceDataSuccess(newData);
                        } catch (error) {
                            console.error('调整后数据刷新失败:', error);
                        }
                    }
                } else {
                    console.error('❌ 床板角度设置失败:', result.error);
                    log(`床板角度设置失败: ${result.error}`, 'error');
                }
                
            } catch (error) {
                console.error('❌ 床板控制错误:', error);
                log(`床板控制错误: ${error.message}`, 'error');
            } finally {
                // 恢复按钮状态
                const actionButtons = document.querySelectorAll('.control-group button');
                actionButtons.forEach(btn => btn.disabled = false);
            }
        }
        
        // 紧急停止
        async function emergencyStop() {
            if (!confirm('确定要执行紧急停止吗？这将停止设备运动。')) {
                return;
            }
            
            try {
                console.log('🛑 执行紧急停止');
                
                // 显示加载中状态
                const actionButtons = document.querySelectorAll('.control-group button');
                actionButtons.forEach(btn => btn.disabled = true);
                
                // 获取当前角度并设置最慢速度来实现"停止"效果
                const currentAngle = document.getElementById('angleSlider').value;
                
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
                
                const response = await fetch('/api/adjust-bed', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        device_id: 'device1',
                        angle: parseInt(currentAngle),
                        speed_level: 1  // 最慢速度
                    }),
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    console.log('✅ 紧急停止执行成功');
                    log('紧急停止已执行，设备已停止', 'warning');
                    // 重置速度选择为最慢
                    document.getElementById('speedSelect').value = 1;
                    
                    // 触发数据刷新
                    if (dataPollingService && dataPollingService.isActive()) {
                        try {
                            const newData = await fetchDeviceData();
                            handleDeviceDataSuccess(newData);
                        } catch (error) {
                            console.error('调整后数据刷新失败:', error);
                        }
                    }
                } else {
                    console.error('❌ 紧急停止执行失败:', result.error);
                    log(`紧急停止失败: ${result.error}`, 'error');
                }
                
            } catch (error) {
                console.error('❌ 紧急停止错误:', error);
                log(`紧急停止失败: ${error.message}`, 'error');
            } finally {
                // 恢复按钮状态
                const actionButtons = document.querySelectorAll('.control-group button');
                actionButtons.forEach(btn => btn.disabled = false);
            }
        }
        
        // 自动控制功能
        async function fetchAutoControlStatus() {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
            
            try {
                const response = await fetch('/api/auto-control/status', {
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.status !== 'success') {
                    throw new Error(data.error || '获取自动控制状态失败');
                }
                
                return data.data.settings.ENABLED;
            } catch (error) {
                clearTimeout(timeoutId);
                console.error('获取自动控制状态失败:', error);
                throw error;
            }
        }

        function updateAutoControlUI(enabled) {
            const statusElement = document.getElementById('autoControlStatus');
            const toggleButton = document.getElementById('toggleAutoControl');
            
            if (statusElement && toggleButton) {
                statusElement.textContent = enabled ? '已启用' : '已禁用';
                statusElement.className = enabled ? 'status-active' : 'status-inactive';
                
                toggleButton.textContent = enabled ? '禁用' : '启用';
                toggleButton.className = 'btn btn-sm ' + (enabled ? 'btn-danger' : 'btn-success');
                
                // 添加日志
                log(`自动坐起控制当前${enabled ? '已启用' : '已禁用'}`, enabled ? 'success' : 'info');
            }
        }

        async function toggleAutoControl() {
            const toggleButton = document.getElementById('toggleAutoControl');
            const isCurrentlyEnabled = toggleButton.textContent === '禁用';
            
            try {
                // 禁用按钮，显示加载状态
                toggleButton.disabled = true;
                toggleButton.textContent = '处理中...';
                
                const url = isCurrentlyEnabled ? '/api/auto-control/disable' : '/api/auto-control/enable';
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
                
                const response = await fetch(url, { 
                    method: 'POST',
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    // 更新UI
                    updateAutoControlUI(!isCurrentlyEnabled);
                    log(`自动控制已${!isCurrentlyEnabled ? '启用' : '禁用'}`, 'success');
                } else {
                    log(`自动控制操作失败: ${data.error}`, 'error');
                    // 恢复原状态
                    updateAutoControlUI(isCurrentlyEnabled);
                }
            } catch (error) {
                log(`自动控制请求失败: ${error.message}`, 'error');
                // 恢复原状态
                updateAutoControlUI(isCurrentlyEnabled);
            } finally {
                // 重新启用按钮
                toggleButton.disabled = false;
            }
        }
        
        // 日志显示函数
        function log(message, type = 'info') {
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        // 页面卸载时清理资源
        window.addEventListener('beforeunload', function() {
            if (dataUpdateInterval) {
                clearInterval(dataUpdateInterval);
            }
        });
        
        // 测试数据显示函数
        async function testDataDisplay() {
            try {
                console.log('🧪 正在获取测试数据...');
                updateConnectionStatus('connecting');
                
                // 首先尝试获取测试数据
                const testResponse = await fetch('/api/test-data');
                if (!testResponse.ok) {
                    throw new Error(`测试数据API错误: ${testResponse.status}`);
                }
                
                const testData = await testResponse.json();
                console.log('🧪 测试数据原始响应:', testData);
                
                // 然后尝试获取当前数据
                const currentResponse = await fetch('/api/current-data');
                if (!currentResponse.ok) {
                    console.warn(`当前数据API错误: ${currentResponse.status}`);
                }
                
                const currentData = await currentResponse.json();
                console.log('🧪 当前数据原始响应:', currentData);
                
                // 更新调试面板，显示两种数据进行对比
                document.getElementById('debugPanel').style.display = 'block';
                
                // 分析测试数据和当前数据的格式
                const testHasPropertyModel = testData && testData.Data && testData.Data.List && Array.isArray(testData.Data.List.PropertyStatusInfo);
                const currentHasPropertyModel = currentData && currentData.Data && currentData.Data.List && Array.isArray(currentData.Data.List.PropertyStatusInfo);
                
                // 获取需要的核心字段
                const getKeyFields = (data, isPropertyModel) => {
                    // 用于存储核心字段
                    const keyFields = {
                        radar_heartrate: null,
                        radar_breath: null,
                        temp: null,
                        humidity: null
                    };
                    
                    // 处理物模型格式
                    if (isPropertyModel) {
                        data.Data.List.PropertyStatusInfo.forEach(item => {
                            if (Object.keys(keyFields).includes(item.Identifier) && item.Value !== undefined) {
                                keyFields[item.Identifier] = {
                                    value: item.Value,
                                    name: item.Name || '',
                                    dataType: item.DataType || '',
                                    time: item.Time || ''
                                };
                            }
                        });
                    } 
                    // 处理旧格式
                    else if (data.devices && data.devices.device1) {
                        const device = data.devices.device1;
                        keyFields.radar_heartrate = {
                            value: device.heart_rate || device.radar_heartrate || null,
                            name: '雷达心率',
                            dataType: 'int',
                            source: '旧格式'
                        };
                        keyFields.radar_breath = {
                            value: device.breath_rate || device.radar_breath || null,
                            name: '雷达呼吸',
                            dataType: 'int',
                            source: '旧格式'
                        };
                        keyFields.temp = {
                            value: device.temperature || device.temp || null,
                            name: '温度',
                            dataType: 'int',
                            source: '旧格式'
                        };
                        keyFields.humidity = {
                            value: device.humidity || null,
                            name: '湿度',
                            dataType: 'int',
                            source: '旧格式'
                        };
                    }
                    
                    return keyFields;
                };
                
                // 提取核心字段数据
                const testKeyFields = getKeyFields(testData, testHasPropertyModel);
                const currentKeyFields = getKeyFields(currentData, currentHasPropertyModel);
                
                // 显示核心字段比较
                const device1Debug = document.getElementById('device1Debug');
                if (device1Debug) {
                    device1Debug.innerHTML = '<strong>测试数据核心字段:</strong><br>' + 
                        JSON.stringify(testKeyFields, null, 2) + 
                        '<br><br><strong>当前数据核心字段:</strong><br>' + 
                        JSON.stringify(currentKeyFields, null, 2);
                }
                
                // 显示完整数据结构
                const device2Debug = document.getElementById('device2Debug');
                if (device2Debug) {
                    // 测试数据格式分析
                    let testFormat = "未知格式";
                    if (testHasPropertyModel) {
                        testFormat = "物模型格式 (PropertyStatusInfo 数组)";
                    } else if (testData.devices) {
                        testFormat = "旧格式 (devices 对象结构)";
                    }
                    
                    // 当前数据格式分析
                    let currentFormat = "未知格式";
                    if (currentHasPropertyModel) {
                        currentFormat = "物模型格式 (PropertyStatusInfo 数组)";
                    } else if (currentData.devices) {
                        currentFormat = "旧格式 (devices 对象结构)";
                    }
                    
                    device2Debug.innerHTML = '<strong>测试数据格式:</strong> ' + testFormat + '<br>' +
                        '<strong>当前数据格式:</strong> ' + currentFormat;
                }
                
                // 添加额外的数据结构分析
                const structureAnalysis = document.createElement('div');
                structureAnalysis.innerHTML = `
                    <h4>数据结构分析</h4>
                    <pre style="font-size: 11px; background: #f5f5f5; padding: 8px; border-radius: 4px;">
测试数据结构:
- 顶层属性: ${Object.keys(testData).join(', ')}
- 数据格式: ${testHasPropertyModel ? '物模型 (PropertyStatusInfo)' : (testData.devices ? '旧格式 (devices)' : '未知格式')}
${testHasPropertyModel ? '- 物模型属性数量: ' + testData.Data.List.PropertyStatusInfo.length : ''}
${testData.devices ? '- devices设备数量: ' + Object.keys(testData.devices).length : ''}

当前数据结构:
- 顶层属性: ${Object.keys(currentData).join(', ')}
- 数据格式: ${currentHasPropertyModel ? '物模型 (PropertyStatusInfo)' : (currentData.devices ? '旧格式 (devices)' : '未知格式')}
${currentHasPropertyModel ? '- 物模型属性数量: ' + currentData.Data.List.PropertyStatusInfo.length : ''}
${currentData.devices ? '- devices设备数量: ' + Object.keys(currentData.devices).length : ''}
                    </pre>
                `;
                
                const debugContent = document.querySelector('.debug-content');
                // 检查是否已存在分析区域
                const existingAnalysis = document.querySelector('.debug-content h4:last-of-type');
                if (existingAnalysis && existingAnalysis.textContent === '数据结构分析') {
                    existingAnalysis.parentElement.removeChild(existingAnalysis.nextElementSibling);
                    existingAnalysis.parentElement.removeChild(existingAnalysis);
                }
                debugContent.appendChild(structureAnalysis);
                
                // 更新最后刷新时间
                document.getElementById('lastUpdateTime').textContent = new Date().toLocaleString('zh-CN');
                
                // 使用测试数据更新UI
                updateDisplayData(testData);
                updateConnectionStatus('online');
                
                return testData;
            } catch (error) {
                console.error('❌ 测试数据获取失败:', error);
                updateConnectionStatus('error');
                alert(`测试数据获取失败: ${error.message}\n请检查后端服务是否运行。`);
            }
        }
        
        // 调试面板功能
        function toggleDebugPanel() {
            const panel = document.getElementById('debugPanel');
            if (panel.style.display === 'none') {
                panel.style.display = 'block';
                // 如果有数据，立即更新调试面板
                if (lastDeviceData) {
                    updateDebugPanel(lastDeviceData);
                }
            } else {
                panel.style.display = 'none';
            }
        }
        
        // 更新调试面板
        function updateDebugPanel(data) {
            try {
                // 如果调试面板不可见，不进行更新
                if (document.getElementById('debugPanel').style.display === 'none') {
                    return;
                }
                
                // 显示API数据结构
                const apiStructure = document.getElementById('apiStructure');
                if (apiStructure) {
                    let structureInfo = '';
                    
                    if (data) {
                        // 分析数据结构
                        structureInfo += '数据类型: ' + typeof data + '\n';
                        
                        if (typeof data === 'object') {
                            structureInfo += '顶级属性: ' + Object.keys(data).join(', ') + '\n\n';
                            
                            // 首先检查物模型数据结构
                            const hasPropertyModel = data.Data && data.Data.List && Array.isArray(data.Data.List.PropertyStatusInfo);
                            
                            if (hasPropertyModel) {
                                structureInfo += '检测到物模型数据结构\n';
                                structureInfo += '数据源: Spark设备物模型\n';
                                structureInfo += `PropertyStatusInfo 数量: ${data.Data.List.PropertyStatusInfo.length}\n\n`;
                                
                                // 数据访问测试 - 物模型格式
                                structureInfo += '物模型数据字段访问测试:\n';
                                
                                // 检查关键字段
                                const keyFields = ['radar_heartrate', 'radar_breath', 'temp', 'humidity'];
                                const foundFields = {};
                                
                                data.Data.List.PropertyStatusInfo.forEach(item => {
                                    if (keyFields.includes(item.Identifier)) {
                                        foundFields[item.Identifier] = item.Value;
                                    }
                                });
                                
                                // 显示找到的关键字段
                                keyFields.forEach(field => {
                                    structureInfo += `${field}: ${foundFields[field] !== undefined ? foundFields[field] : '未找到'}\n`;
                                });
                                
                                // 物模型详细信息
                                structureInfo += '\n物模型详细字段:\n';
                                data.Data.List.PropertyStatusInfo.forEach(item => {
                                    structureInfo += `${item.Identifier} (${item.Name || '无名称'}): ${item.Value} (${item.DataType})\n`;
                                });
                                
                                structureInfo += '\n注意: 只显示 radar_heartrate, radar_breath, temp, humidity\n';
                            }
                            // 备用: 检查旧的设备数据结构
                            else if (data.devices) {
                                structureInfo += '使用备用数据结构 (旧格式)\n';
                                structureInfo += 'devices属性: ' + typeof data.devices + '\n';
                                structureInfo += 'devices包含: ' + Object.keys(data.devices).join(', ') + '\n';
                                
                                // 备用数据访问测试
                                structureInfo += '\n备用数据访问测试:\n';
                                try {
                                    structureInfo += 'data.devices.device1.heart_rate = ' + 
                                        (data.devices && data.devices.device1 ? data.devices.device1.heart_rate : '未找到') + '\n';
                                    
                                    structureInfo += 'data.devices.device1.temperature = ' + 
                                        (data.devices && data.devices.device1 ? data.devices.device1.temperature : '未找到') + '\n';
                                    
                                    structureInfo += 'data.devices.device1.humidity = ' + 
                                        (data.devices && data.devices.device1 ? data.devices.device1.humidity : '未找到') + '\n';
                                    
                                } catch (e) {
                                    structureInfo += '访问异常: ' + e.message + '\n';
                                }
                            } else {
                                structureInfo += '⚠️ 未识别的数据格式\n';
                            }
                        }
                    } else {
                        structureInfo = '没有数据可用';
                    }
                    
                    apiStructure.innerHTML = `<pre>${structureInfo}</pre>`;
                }
                
                // 更新物模型数据显示
                if (data && data.Data && data.Data.List && Array.isArray(data.Data.List.PropertyStatusInfo)) {
                    // 提取我们关心的四个关键字段
                    const keyFields = ['radar_heartrate', 'radar_breath', 'temp', 'humidity'];
                    const extractedData = {};
                    
                    // 从物模型中提取关键字段
                    data.Data.List.PropertyStatusInfo.forEach(item => {
                        if (keyFields.includes(item.Identifier)) {
                            let value = item.Value;
                            // 尝试转换为数值
                            if (item.DataType === 'int' && typeof value === 'string' && !isNaN(Number(value))) {
                                value = Number(value);
                            }
                            
                            extractedData[item.Identifier] = {
                                value: value,
                                dataType: item.DataType,
                                name: item.Name || '',
                                time: item.Time || ''
                            };
                        }
                    });
                    
                    // 显示提取的物模型数据
                    document.getElementById('device1Debug').innerHTML = 
                        `<pre>Spark设备核心数据 (物模型格式):\n${JSON.stringify(extractedData, null, 2)}</pre>`;
                    
                    // 在设备2区域显示完整的物模型数据
                    document.getElementById('device2Debug').innerHTML = 
                        `<pre>物模型完整数据 (${data.Data.List.PropertyStatusInfo.length} 个属性):\n` +
                        `${JSON.stringify(data.Data.List.PropertyStatusInfo
                            .filter(item => item.Value !== undefined)
                            .slice(0, 10), null, 2)}\n` +
                        `...（显示前10条）</pre>`;
                }
                // 备用: 显示旧格式数据
                else if (data && data.devices) {
                    console.warn('⚠️ 使用备用数据格式显示，应当切换到物模型格式');
                    
                    // 更新设备1数据（仅显示关键字段）
                    if (data.devices.device1) {
                        const device1Data = data.devices.device1;
                        const filteredData = {
                            heart_rate: device1Data.heart_rate || 0,
                            breath_rate: device1Data.breath_rate || 0,
                            temperature: device1Data.temperature || 0,
                            humidity: device1Data.humidity || 0
                        };
                        
                        document.getElementById('device1Debug').innerHTML = 
                            `<pre>设备1关键数据 (备用格式):\n${JSON.stringify(filteredData, null, 2)}</pre>`;
                    }
                    
                    // 更新设备2数据
                    if (data.devices.device2) {
                        document.getElementById('device2Debug').innerHTML = 
                            `<pre>设备2数据 (仅坐起状态):\n${JSON.stringify({sitting_up: data.devices.device2.sitting_up}, null, 2)}</pre>`;
                    }
                }
                
                // 更新最后刷新时间
                document.getElementById('lastUpdateTime').textContent = new Date().toLocaleString('zh-CN');
                
            } catch (error) {
                console.error('更新调试面板失败:', error);
            }
        }
    </script>
    
    <!-- 数据调试工具脚本 -->
    <script src="data_debugger_new.js"></script>
    
    <script>
        // 添加调试面板快捷键 (按 Ctrl+Shift+D 显示调试面板)
        document.addEventListener('keydown', function(event) {
            if (event.ctrlKey && event.shiftKey && event.key === 'D') {
                event.preventDefault();
                if (window.dataDebugger) {
                    // 如果调试面板尚未初始化，先获取数据
                    const debugPanel = document.getElementById('data-debug-panel');
                    if (!debugPanel && dataPollingService) {
                        fetchDeviceData().then(data => {
                            window.dataDebugger.processResponse(data);
                        }).catch(error => {
                            console.error('获取数据失败:', error);
                            alert('获取数据失败: ' + error.message);
                        });
                    } else {
                        // 如果面板已初始化，直接显示
                        window.dataDebugger.showDebugPanel();
                    }
                } else {
                    alert('调试工具未加载');
                }
            }
        });
        
        // 添加调试按钮
        document.addEventListener('DOMContentLoaded', function() {
            const debugButton = document.createElement('button');
            debugButton.textContent = '打开调试面板';
            debugButton.style.position = 'fixed';
            debugButton.style.bottom = '10px';
            debugButton.style.right = '10px';
            debugButton.style.zIndex = '999';
            debugButton.style.padding = '8px 12px';
            debugButton.style.background = '#673ab7';
            debugButton.style.color = 'white';
            debugButton.style.border = 'none';
            debugButton.style.borderRadius = '4px';
            debugButton.style.cursor = 'pointer';
            debugButton.style.boxShadow = '0 2px 5px rgba(0,0,0,0.3)';
            
            debugButton.addEventListener('click', function() {
                if (window.dataDebugger) {
                    const debugPanel = document.getElementById('data-debug-panel');
                    if (!debugPanel) {
                        // 如果调试面板尚未初始化，先获取数据
                        fetchDeviceData().then(data => {
                            window.dataDebugger.processResponse(data);
                        }).catch(error => {
                            console.error('获取数据失败:', error);
                            alert('获取数据失败: ' + error.message);
                        });
                    } else {
                        // 如果面板已初始化，直接显示
                        window.dataDebugger.showDebugPanel();
                    }
                } else {
                    alert('调试工具未加载');
                }
            });
            
            document.body.appendChild(debugButton);
        });
    </script>
</body>
</html>
